<template>
  <div>
    <div class="head">
      <form action="/">
        <van-search
          shape="round"
          v-model="searchValue"
          placeholder="请输入搜索关键词"
          @search="methods.onSearch"
        />
      </form>
    </div>
    <div class="content-box">
      <div class="broadside" :style="{ 'min-height': inHeight }">
        <van-sidebar v-model="activeKey" @change="methods.onChange">
          <van-sidebar-item :title="'推荐'" />
          <van-sidebar-item
            :title="v.title"
            v-for="v in navList"
            :key="v.value"
          />
        </van-sidebar>
      </div>
      <div class="right-shop">
        <div class="shop-box">
          <div class="item" v-for="(v, i) in childData" :key="i">
            <div class="img-box">
              <img :src="v.image_url" alt="" @click="methods.next(v)" />
            </div>
            <p class="pro-name">
              {{ v.name }}
            </p>
            <p class="pro-enname">
              {{ v.description }}
            </p>
            <p class="pro-price">￥{{ v.price }}</p>
            <!-- <span class="add-shop">+</span> -->
            <span class="add-shop" @click="methods.getRule(v.id)">+</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { showSuccessToast, showToast } from 'vant'
import { CoffeeModel, GET, postFormData } from '@/api'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { MenuNavListModel } from './model'
import { getToken } from '@/utils/token'

const searchValue = ref('')
const activeKey = ref(0)
/** 左侧导航栏 */
const navList = ref<MenuNavListModel[]>([])
const childData = ref<CoffeeModel[]>([])
/** 推荐商品 */
const recommendShop = ref<CoffeeModel[]>([])
const inHeight = innerHeight + 'px'

const router = useRouter()

const methods = {
  onSearch(val: string) {
    router.push({ name: 'Search', query: { name: val } })
  },
  onChange(_index: number) {
    methods.getChildData()
  },
  next(v: CoffeeModel) {
    router.push({ name: 'ShopMes', query: { pid: v.id } })
  },
  getNavList() {
    GET({
      url: '/menus'
    })
      .then((res) => {
        console.log(res, 'navList')
        navList.value = res?.data
        methods.getChildData()
      })
      .catch((err) => {
        console.error(err)
      })
  },
  getChildData() {
    if (activeKey.value === 0) {
      childData.value = recommendShop.value
      return
    }
    GET({
      url: '/list',
      params: {
        menuId: navList.value[activeKey.value - 1].value
      }
    })
      .then((res) => {
        childData.value = res?.data?.list || []
        childData.value =
          childData.value?.map((item) => {
            return {
              ...item,
              image_url: import.meta.env.VITE_APP_PROXY_URL + item.image_url
            }
          }) ?? []
      })
      .catch((err) => {
        console.error(err)
      })
  },
  async getRecommend() {
    try {
      const res = await GET({
        url: '/recommendations'
      })
      recommendShop.value = res.data.list
      recommendShop.value =
        recommendShop.value?.map((item) => {
          return {
            ...item,
            image_url: import.meta.env.VITE_APP_PROXY_URL + item.image_url
          }
        }) ?? []

      console.log(recommendShop.value, 'datasource')
      methods.getChildData()
    } catch (err) {
      console.error(err)
    }
  },
  getRule(pid: number) {
    // const arr = ['cream', 'milk', 'sugar', 'tem']
    // let obj: Record<string, any> = {}
    // const rules: string[] = []
    // let str = ''
    // GET({
    //   url: '/productDetail',
    //   params: {
    //     appkey,
    //     pid
    //   }
    // })
    //   .then((res) => {
    //     obj = res.data.result[0]
    //     arr.forEach((item) => {
    //       if (obj[item]) {
    //         const rule = obj[item].split('/')[0]
    //         rules.push(rule)
    //       }
    //     })
    //     str = rules.join('/')
    //     methods.addShop(pid, str)
    //   })
    //   .catch((err) => {
    //     console.error(err)
    //   })
    methods.addShop(pid)
  },
  addShop(pid: number) {
    if (!getToken()) {
      showToast('请先登录')
    } else {
      postFormData({
        url: '/shop/add',
        params: {
          pid,
          count: 1
        }
      })
        .then(() => {
          showSuccessToast('已添加购物车')
        })
        .catch((err) => {
          console.error(err)
        })
    }
  }
}

onMounted(async () => {
  await methods.getRecommend()
  methods.getNavList()
})
</script>

<style lang="less" scoped>
.head {
  width: 100%;
  //   height: 40px;
  box-sizing: border-box;
  border-bottom: 1px solid #ddd;
  text-align: center;
  padding: 0 20px;
  padding-top: 10px;
}
:deep(.van-search) {
  padding: 0;
  background-color: transparent;
}
.content-box {
  width: 100%;
  padding-top: 10px;
  display: flex;
  .broadside {
    background-color: #fff;
  }
  .right-shop {
    width: 90%;
    .shop-box {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      padding: 0 10px;
      box-sizing: border-box;
      margin-bottom: 50px;
      .item {
        width: calc(~'100% / 2 - 10px');
        text-align: center;
        padding: 10px 2px;
        font-size: 16px;
        margin-bottom: 10px;
        border-radius: 10px;
        background-color: #fff;
        position: relative;
        .pro-enname {
          font-size: 12px;
        }
        p {
          margin: 2px 0;
          text-align: left;
          padding-left: 10%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .img-box {
          width: 80%;
          margin: 0 auto;
          img {
            width: 100%;
          }
        }
        .pro-price {
          color: rgb(12, 52, 186);
          font-weight: bold;
        }
        .add-shop {
          width: 20px;
          height: 20px;
          position: absolute;
          bottom: 10px;
          right: 10px;
          display: block;
          border-radius: 50%;
          background-color: #e4393c;
          color: #fff;
          font-size: 20px;
          line-height: 20px;
          text-align: center;
          cursor: pointer;
        }
      }
    }
  }
}
:deep(.van-sidebar-item--select)::before {
  background-color: rgb(12, 52, 186);
}
</style>
